package com.rskj.cashbook.controller;

import com.rskj.cashbook.iexception.BusinessException;
import com.rskj.cashbook.response.ResponseEntity;
import com.rskj.cashbook.service.ISqlMonitorLogService;

import com.rskj.cashbook.vo.SqlTxtMonitorLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/sql/monitor")
public class SqlMonitorController {

    @Autowired
    private ISqlMonitorLogService sqlMonitorLogService;

    /**
     * 查询SQL监控日志
     */
    @PostMapping("/logs")
    public ResponseEntity<List<SqlTxtMonitorLog>> querySqlLogs(@RequestBody SqlTxtMonitorLog condition) {
        try {
            List<SqlTxtMonitorLog> logs = sqlMonitorLogService.querySqlLogs(condition);
            return ResponseEntity.ok(logs);
        } catch (Exception e) {
            log.error("查询SQL监控日志失败: {}", e.getMessage(), e);
            throw new BusinessException("查询SQL监控日志失败: " + e.getMessage());
        }
    }

    /**
     * 查询慢查询SQL
     */
    @GetMapping("/slow-queries")
    public ResponseEntity<List<SqlTxtMonitorLog>> getSlowQueries(
            @RequestParam(value = "threshold", defaultValue = "1000") Long threshold) {
        try {
            List<SqlTxtMonitorLog> logs = sqlMonitorLogService.getSlowQueries(threshold);
            return ResponseEntity.ok(logs);
        } catch (Exception e) {
            log.error("查询慢查询SQL失败: {}", e.getMessage(), e);
            throw new BusinessException("查询慢查询SQL失败: " + e.getMessage());
        }
    }

    /**
     * 查询错误SQL
     */
    @GetMapping("/error-queries")
    public ResponseEntity<List<SqlTxtMonitorLog>> getErrorQueries() {
        try {
            List<SqlTxtMonitorLog> logs = sqlMonitorLogService.getErrorQueries();
            return ResponseEntity.ok(logs);
        } catch (Exception e) {
            log.error("查询错误SQL失败: {}", e.getMessage(), e);
            throw new BusinessException("查询错误SQL失败: " + e.getMessage());
        }
    }

    /**
     * 获取SQL执行统计信息
     */
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getStatistics(
            @RequestParam(value = "startTime", required = false) String startTimeStr) {
        try {
            LocalDateTime startTime = null;
            if (startTimeStr != null && !startTimeStr.isEmpty()) {
                startTime = LocalDateTime.parse(startTimeStr);
            }

            Map<String, Object> statistics = sqlMonitorLogService.getSqlStatistics(startTime);
            return ResponseEntity.ok(statistics);
        } catch (Exception e) {
            log.error("获取SQL统计信息失败: {}", e.getMessage(), e);
            throw new BusinessException("获取SQL统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 手动清理过期日志
     */
    @PostMapping("/cleanup")
    public ResponseEntity<Integer> cleanupExpiredLogs(
            @RequestParam(value = "expireTime", required = false) String expireTimeStr) {
        try {
            LocalDateTime expireTime = null;
            if (expireTimeStr != null && !expireTimeStr.isEmpty()) {
                expireTime = LocalDateTime.parse(expireTimeStr);
            }

            int deletedCount = sqlMonitorLogService.cleanExpiredLogs(expireTime);
            return ResponseEntity.ok(deletedCount);
        } catch (Exception e) {
            log.error("清理过期日志失败: {}", e.getMessage(), e);
            throw new BusinessException("清理过期日志失败: " + e.getMessage());
        }
    }

    /**
     * 获取SQL监控配置信息
     */
    @GetMapping("/config")
    public ResponseEntity<Map<String, Object>> getConfig() {
        try {
            Map<String, Object> config = Map.of(
                    "enabled", true,
                    "slowQueryThreshold", 1000L,
                    "retentionDays", 30,
                    "batchSize", 100
            );
            return ResponseEntity.ok(config);
        } catch (Exception e) {
            log.error("获取配置信息失败: {}", e.getMessage(), e);
            throw new BusinessException("获取配置信息失败: " + e.getMessage());
        }
    }
}

